package com.dragoncombin.homework.Module04.Problem04;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerTest {

    public static void main(String[] args) {
        ServerSocket ss = null;
        Socket socket = null;
        ObjectInputStream ois = null;
        ObjectOutputStream oos = null;

        try {
            // 1. 创建ServerSocket 类型的对象，指定端口号
            ss = new ServerSocket(8989);
            // 2. 接收客户端的连接，进入阻塞状态
            System.out.println("等待客户端连接中...");
            socket = ss.accept();
            // 3. 客户端连接成功后，使用Socket输入输入出流与客户端进行通信
            System.out.println("客户端" + socket.getInetAddress() + "连接成功");

            // 创建用于接收客户端发送的对象流
            ois = new ObjectInputStream(socket.getInputStream());
            oos = new ObjectOutputStream(socket.getOutputStream());
            while(true) {
                // 使用对象输入流接收客户端传入的信息
                UserMessage obj = (UserMessage) ois.readObject();
                // 判断获取到的对象中User对象的信息是否符合登录要求
                User user = obj.getUser();
                if ("admin".equals(user.getUserName()) && "123456".equals(user.getPassword())) {
                    obj.setType("success");
                    System.out.println("给客户端" + socket.getInetAddress() + "发送回执...");
                    oos.writeObject(obj);
                    System.out.println("关闭服务器线程");
                    break;
                } else {
                    obj.setType("fail");
                }
                System.out.println("给客户端" + socket.getInetAddress() + "发送回执...");
                // 将修改后的obj重新发回客户端
                oos.writeObject(obj);
                System.out.println("回执发送成功");
            }
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            // 4. 关闭Socket并释放资源
            if (null != oos) {
                try {
                    oos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != ois) {
                try {
                    ois.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != socket) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != ss) {
                try {
                    ss.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}
